library(dplyr)
library(car)
library(rstatix)
library(emmeans)
library(ggplot2)
library(knitr)
library(kableExtra)
library(htmltools)
## -- Attaching packages --------------------------------------- tidyverse 1.3.1 --
## v tibble 3.1.6 v purrr 0.3.4
## v tidyr 1.1.4 v stringr 1.4.0
## v readr 2.1.1 v forcats 0.5.1
## -- Conflicts ------------------------------------------ tidyverse_conflicts() --
## x rstatix::filter() masks dplyr::filter(), stats::filter()
## x kableExtra::group_rows() masks dplyr::group_rows()
## x dplyr::lag() masks stats::lag()
## x car::recode() masks dplyr::recode()
## x purrr::some() masks car::some()
1.Vamos trabalhar de novo com os dados eleitorais do Tribunal Superior Eleitoral, o qual disponibiliza dados sobre os resultados eleitorais separadamente dos dados sobre os candidatos. Baixe os dados de Resultados e Candidatos de Roraima. Observe que os dados são processados (não sendo os originais) e contém apenas a informação de vereadores.
2.Abra os dois bancos em R com o separador apropriado (note que o formato é um pouco diferente dos arquivos no desafio 1 - o encoding é o padrão, UTF8. Logo, não é preciso mexer nisso).
library("tidyverse")
library("tidylog")
##
## Attaching package: 'tidylog'
## The following objects are masked from 'package:tidyr':
##
## drop_na, fill, gather, pivot_longer, pivot_wider, replace_na,
## spread, uncount
## The following objects are masked from 'package:rstatix':
##
## drop_na, filter, gather, group_by, mutate, select, spread
## The following objects are masked from 'package:dplyr':
##
## add_count, add_tally, anti_join, count, distinct, distinct_all,
## distinct_at, distinct_if, filter, filter_all, filter_at, filter_if,
## full_join, group_by, group_by_all, group_by_at, group_by_if,
## inner_join, left_join, mutate, mutate_all, mutate_at, mutate_if,
## relocate, rename, rename_all, rename_at, rename_if, rename_with,
## right_join, sample_frac, sample_n, select, select_all, select_at,
## select_if, semi_join, slice, slice_head, slice_max, slice_min,
## slice_sample, slice_tail, summarise, summarise_all, summarise_at,
## summarise_if, summarize, summarize_all, summarize_at, summarize_if,
## tally, top_frac, top_n, transmute, transmute_all, transmute_at,
## transmute_if, ungroup
## The following object is masked from 'package:stats':
##
## filter
resultados <- read_delim("resultados_2016_RR.csv",
delim=";")
## Rows: 1867 Columns: 8
## -- Column specification --------------------------------------------------------
## Delimiter: ";"
## chr (5): NM_MUNICIPIO, CD_MUNICIPIO, DS_SIT_TOT_TURNO, NM_CANDIDATO, SG_PARTIDO
## dbl (3): SQ_CANDIDATO, NR_ZONA, QT_VOTOS_NOMINAIS
##
## i Use `spec()` to retrieve the full column specification for this data.
## i Specify the column types or set `show_col_types = FALSE` to quiet this message.
candidatos <- read_delim("candidatos_2016_RR.csv",
delim=";")
## Rows: 1626 Columns: 63
## -- Column specification --------------------------------------------------------
## Delimiter: ";"
## chr (38): DT_GERACAO, NM_TIPO_ELEICAO, DS_ELEICAO, DT_ELEICAO, TP_ABRANGENC...
## dbl (24): ANO_ELEICAO, CD_TIPO_ELEICAO, NR_TURNO, CD_ELEICAO, CD_CARGO, SQ_...
## time (1): HH_GERACAO
##
## i Use `spec()` to retrieve the full column specification for this data.
## i Specify the column types or set `show_col_types = FALSE` to quiet this message.
resultados
candidatos
candidatos %>% distinct(SQ_CANDIDATO)
resultados %>% distinct(SQ_CANDIDATO, CD_MUNICIPIO, NR_ZONA) #Pode excluir CD_MUNICIPIO, mas fica mais claro incluir
#SQ_CANDIDATO
anti_join para identificar se há resultados que faltam detalhes do seu candidato no banco de dados de candidatos.resultados %>% anti_join(candidatos, by="SQ_CANDIDATO")
anti_join para identificar se há candidatos faltando no banco de dados de resultados. Investigando as colunas do resultado de anti_join, você pode identificar porque eles não existem no banco de resultados?)candidatos %>% anti_join(resultados, by="SQ_CANDIDATO")
Os candidatos sem resultados são aqueles ‘inaptos’ para a eleição.
candidatos <- candidatos %>% select(SQ_CANDIDATO, NM_CANDIDATO, NM_UE, SG_PARTIDO,
NR_IDADE_DATA_POSSE, DS_GENERO, DS_GRAU_INSTRUCAO,
DS_COR_RACA)
## select: dropped 55 variables (DT_GERACAO, HH_GERACAO, ANO_ELEICAO, CD_TIPO_ELEICAO, NM_TIPO_ELEICAO, …)
candidatos
left_join() apropriado.resultados %>% left_join(candidatos, by="SQ_CANDIDATO")
resultados_totais <- resultados %>% group_by(SQ_CANDIDATO, DS_SIT_TOT_TURNO) %>%
summarize(QT_VOTOS_NOMINAIS=sum(QT_VOTOS_NOMINAIS, na.rm=T)) %>%
ungroup()
## group_by: 2 grouping variables (SQ_CANDIDATO, DS_SIT_TOT_TURNO)
## summarize: now 1,512 rows and 3 columns, one group variable remaining (SQ_CANDIDATO)
## ungroup: no grouping variables
resultados_totais
left_join() apropriado para incorporar os dados dos candidatos.resultados_totais_candidatos <- resultados_totais %>% left_join(candidatos, by="SQ_CANDIDATO")
## left_join: added 7 columns (NM_CANDIDATO, NM_UE, SG_PARTIDO, NR_IDADE_DATA_POSSE, DS_GENERO, …)
## > rows only in x 0
## > rows only in y ( 114)
## > matched rows 1,512
## > =======
## > rows total 1,512
resultados_totais_candidatos
candidatos_resultados_totais <- candidatos %>% left_join(resultados_totais, by="SQ_CANDIDATO")
## left_join: added 2 columns (DS_SIT_TOT_TURNO, QT_VOTOS_NOMINAIS)
## > rows only in x 114
## > rows only in y ( 0)
## > matched rows 1,512
## > =======
## > rows total 1,626
#OU
candidatos_resultados_totais <- resultados_totais %>% right_join(candidatos, by="SQ_CANDIDATO")
## right_join: added 7 columns (NM_CANDIDATO, NM_UE, SG_PARTIDO, NR_IDADE_DATA_POSSE, DS_GENERO, …)
## > rows only in x ( 0)
## > rows only in y 114
## > matched rows 1,512
## > =======
## > rows total 1,626
candidatos_resultados_totais
QT_VOTOS_NOMINAIS foi preenchida em 6(a) para os candidatos que não receberam votos no banco resultados? Sabendo que esses candidatos não receberam voto, recodifique a coluna para inserir zero votos nos locais apropriados da coluna QT_VOTOS_NOMINAIS.candidatos_resultados_totais <- candidatos_resultados_totais %>%
mutate(QT_VOTOS_NOMINAIS=case_when(is.na(QT_VOTOS_NOMINAIS)~0,
TRUE~QT_VOTOS_NOMINAIS))
## mutate: changed 114 values (7%) of 'QT_VOTOS_NOMINAIS' (114 fewer NA)
candidatos_resultados_totais
NM_UE).Escolha um tipo de gráfico apropriado e crie o gráfico.
Adicione um título ao seu gráfico, e rótulos nos eixos.
Use o código da camada + theme(axis.text.x = element_text(angle = 90)) para virar o texto do município vertical e deixar mais visível.
resultados_totais_candidatos %>%
ggplot() +
geom_bar(aes(x=NM_UE)) +
ggtitle("Número de Candidatos por Município") +
xlab("Município") +
ylab("Número de Candidatos") +
theme(axis.text.x = element_text(angle = 90))
DS_GENERO) no estado inteiro. Prepare um gráfico apropriado, com título, rótulos nos eixos e aplique um tema simples da sua escolha.resultados_totais_candidatos %>%
ggplot() +
geom_bar(aes(x=DS_GENERO)) +
ggtitle("Número de Candidatos por Gênero") +
xlab("Gênero") +
ylab("Número de Candidatos") +
theme_classic()
resultados_totais_candidatos %>% group_by(NM_UE, DS_GENERO) %>%
tally() %>%
ggplot() +
geom_col(aes(x=NM_UE, y=n, fill=DS_GENERO), position="fill") +
ggtitle("O Porcentagem de Candidatos por Município e Gênero") +
xlab("Município") +
ylab("Porcentagem de Candidatos") +
theme(axis.text.x = element_text(angle = 90)) +
theme(legend.position="bottom")
## group_by: 2 grouping variables (NM_UE, DS_GENERO)
## tally: now 30 rows and 3 columns, one group variable remaining (NM_UE)
DS_SIT_TOT_TURNO.resultados_totais_candidatos <- resultados_totais_candidatos %>%
mutate(Eleito=case_when(DS_SIT_TOT_TURNO %in%
c("ELEITO POR QP","ELEITO POR MÉDIA", "ELEITO")~1,
TRUE~0))
## mutate: new variable 'Eleito' (double) with 2 unique values and 0% NA
resultados_totais_candidatos
sucesso_por_genero_mun <- resultados_totais_candidatos %>%
group_by(NM_UE, DS_GENERO, Eleito) %>%
tally() %>%
group_by(NM_UE, DS_GENERO) %>%
mutate(Pct_eleito=100*(n/sum(n,na.rm=T))) %>%
ungroup()
## group_by: 3 grouping variables (NM_UE, DS_GENERO, Eleito)
## tally: now 58 rows and 4 columns, 2 group variables remaining (NM_UE, DS_GENERO)
## group_by: 2 grouping variables (NM_UE, DS_GENERO)
## mutate (grouped): new variable 'Pct_eleito' (double) with 49 unique values and 0% NA
## ungroup: no grouping variables
sucesso_por_genero_mun
sucesso_por_genero_mun %>%
filter(DS_GENERO=="FEMININO" & Eleito==1) %>%
ggplot() +
geom_col(aes(x=NM_UE, y=Pct_eleito)) +
ggtitle("O Porcentagem de Candidatos Femininos Eleitos por Município") +
xlab("Município") +
ylab("% de Candidatos Eleitos") +
theme_classic() +
theme(axis.text.x = element_text(angle = 90))
## filter: removed 45 rows (78%), 13 rows remaining
sucesso_por_genero_mun %>%
filter(Eleito==1) %>%
ggplot() +
geom_col(aes(x=NM_UE, y=Pct_eleito, fill=DS_GENERO), position="dodge") +
ggtitle("O Porcentagem de Candidatos Eleitos por Município e Gênero") +
xlab("Município") +
ylab("% de Candidatos Eleitos") +
theme_classic() +
theme(axis.text.x = element_text(angle = 90))
## filter: removed 30 rows (52%), 28 rows remaining
mun_sucesso_feminino <- sucesso_por_genero_mun %>% filter(Eleito==1) %>%
select(-n) %>%
pivot_wider(names_from="DS_GENERO",
values_from="Pct_eleito") %>%
filter(FEMININO>MASCULINO) %>%
pull(NM_UE)
## filter: removed 30 rows (52%), 28 rows remaining
## select: dropped one variable (n)
## pivot_wider: reorganized (DS_GENERO, Pct_eleito) into (FEMININO, MASCULINO) [was 28x4, now 15x4]
## filter: removed 14 rows (93%), one row remaining
mun_sucesso_feminino
## [1] "CAROEBE"
O município em que as mulheres têm uma maior taxa de sucesso que os homens é CAROEBE.
resultados_totais_candidatos %>% group_by(NM_UE, DS_GENERO) %>%
tally() %>%
ggplot() +
geom_tile(aes(x=DS_GENERO, y=NM_UE, fill=n)) +
scale_fill_gradient(low="#efedf5", high="#3f007d") +
ggtitle("Número de Candidatos por Município e Gênero") +
xlab("Município") +
ylab("Número de Candidatos") +
theme_classic()
## group_by: 2 grouping variables (NM_UE, DS_GENERO)
## tally: now 30 rows and 3 columns, one group variable remaining (NM_UE)
NR_IDADE_DATA_POSSE). Faça qualquer ajuste necessário para que o seu gráfico faça sentido e incorpore valores de idade possíveis. Formate o seu gráfico.resultados_totais_candidatos %>%
mutate(NR_IDADE_DATA_POSSE=case_when(NR_IDADE_DATA_POSSE==999~NA_real_,
TRUE~NR_IDADE_DATA_POSSE)) %>%
ggplot() +
geom_histogram(aes(x=NR_IDADE_DATA_POSSE)) +
ggtitle("Histograma de Candidatos por Idade") +
xlab("Idade") +
ylab("Número de Candidatos") +
theme_classic()
## mutate: changed one value (<1%) of 'NR_IDADE_DATA_POSSE' (1 new NA)
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## Warning: Removed 1 rows containing non-finite values (stat_bin).
resultados_totais_candidatos %>%
mutate(NR_IDADE_DATA_POSSE=case_when(NR_IDADE_DATA_POSSE==999~NA_real_,
TRUE~NR_IDADE_DATA_POSSE)) %>%
ggplot() +
geom_histogram(aes(x=NR_IDADE_DATA_POSSE, fill=DS_GENERO),
position="dodge") +
ggtitle("Histograma de Candidatos por Idade") +
xlab("Idade") +
ylab("Número de Candidatos") +
theme_classic()
## mutate: changed one value (<1%) of 'NR_IDADE_DATA_POSSE' (1 new NA)
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## Warning: Removed 1 rows containing non-finite values (stat_bin).
resultados_totais_candidatos %>%
mutate(NR_IDADE_DATA_POSSE=case_when(NR_IDADE_DATA_POSSE==999~NA_real_,
TRUE~NR_IDADE_DATA_POSSE)) %>%
ggplot() +
geom_histogram(aes(x=NR_IDADE_DATA_POSSE, fill=DS_GENERO)) +
ggtitle("Histograma de Candidatos por Idade") +
xlab("Idade") +
ylab("Número de Candidatos") +
theme_classic() +
facet_grid(rows=vars(DS_COR_RACA), cols=vars(DS_GENERO))
## mutate: changed one value (<1%) of 'NR_IDADE_DATA_POSSE' (1 new NA)
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## Warning: Removed 1 rows containing non-finite values (stat_bin).
resultados_totais_candidatos <- resultados_totais_candidatos %>%
group_by(NM_UE) %>%
mutate(Pct_Votos=100*(QT_VOTOS_NOMINAIS/sum(QT_VOTOS_NOMINAIS,na.rm=T)))
## group_by: one grouping variable (NM_UE)
## mutate (grouped): new variable 'Pct_Votos' (double) with 1,063 unique values and 0% NA
resultados_totais_candidatos
candidatos_idade_media_votos <- resultados_totais_candidatos %>%
mutate(NR_IDADE_DATA_POSSE=case_when(NR_IDADE_DATA_POSSE==999~NA_real_,
TRUE~NR_IDADE_DATA_POSSE)) %>%
group_by(NR_IDADE_DATA_POSSE) %>%
summarize(Media_Pct_Votos=mean(Pct_Votos,na.rm=T))
## mutate (grouped): changed one value (<1%) of 'NR_IDADE_DATA_POSSE' (1 new NA)
## group_by: one grouping variable (NR_IDADE_DATA_POSSE)
## summarize: now 59 rows and 2 columns, ungrouped
candidatos_idade_media_votos
candidatos_idade_media_votos %>%
ggplot() +
geom_line(aes(x=NR_IDADE_DATA_POSSE, y=Media_Pct_Votos)) +
ggtitle("Porcentagem de Votos de Candidatos por Idade") +
xlab("Idade") +
ylab("Média de Porcentagem de Votos") +
theme_classic()
## Warning: Removed 1 row(s) containing missing values (geom_path).
candidatos_idade_genero_media_votos <- resultados_totais_candidatos %>%
mutate(NR_IDADE_DATA_POSSE=case_when(NR_IDADE_DATA_POSSE==999~NA_real_,
TRUE~NR_IDADE_DATA_POSSE)) %>%
group_by(DS_GENERO, NR_IDADE_DATA_POSSE) %>%
summarize(Media_Pct_Votos=mean(Pct_Votos,na.rm=T))
## mutate (grouped): changed one value (<1%) of 'NR_IDADE_DATA_POSSE' (1 new NA)
## group_by: 2 grouping variables (DS_GENERO, NR_IDADE_DATA_POSSE)
## summarize: now 109 rows and 3 columns, one group variable remaining (DS_GENERO)
candidatos_idade_genero_media_votos %>%
ggplot() +
geom_line(aes(x=NR_IDADE_DATA_POSSE, y=Media_Pct_Votos, group=DS_GENERO, colour=DS_GENERO))
## Warning: Removed 1 row(s) containing missing values (geom_path).
candidatos_idade_genero_media_votos
candidatos_idade_genero_media_votos %>%
group_by(DS_GENERO) %>%
arrange(DS_GENERO, -Media_Pct_Votos) %>%
top_n(1, Media_Pct_Votos)
## group_by: one grouping variable (DS_GENERO)
## top_n (grouped): removed 107 rows (98%), 2 rows remaining
resultados_totais_partidos <- resultados_totais_candidatos %>% group_by(NM_UE, SG_PARTIDO) %>%
summarize(Tot_Votos=sum(QT_VOTOS_NOMINAIS, na.rm=T)) %>%
group_by(NM_UE) %>%
mutate(Pct_Votos=100*(Tot_Votos/sum(Tot_Votos,na.rm=T))) %>%
ungroup()
## group_by: 2 grouping variables (NM_UE, SG_PARTIDO)
## summarize: now 325 rows and 3 columns, one group variable remaining (NM_UE)
## group_by: one grouping variable (NM_UE)
## mutate (grouped): new variable 'Pct_Votos' (double) with 299 unique values and 0% NA
## ungroup: no grouping variables
resultados_totais_partidos
IDH <- tibble(NM_UE=c("ALTO ALEGRE", "AMAJARI", "BOAVISTA", "BONFIM",
"CANTÁ", "CARACARAÍ", "CAROEBE", "IRACEMA", "MUCAJAÍ",
"NORMANDIA", "PACARAIMA", "RORAINOPOLIS",
"SÃO JOÃO DA BALIZA", "SÃO LUIZ", "UIRAMUTÃ"),
IDH=c(0.542, 0.484, 0.752, 0.626, 0.619, 0.624, 0.639, 0.582, 0.665,
0.594, 0.650, 0.619, 0.655, 0.649, 0.453))
IDH
anti_join() para verificar se existe um identificador comum e completo para os dois bancos de resultados por partido e IDH. Corrija os erros para que todas as observações possam ser cruzadas.resultados_totais_partidos %>% anti_join(IDH, by="NM_UE") %>%
distinct(NM_UE) #Boa Vista e Roraionopolis não cruzados
## anti_join: added no columns
## > rows only in x 59
## > rows only in y ( 2)
## > matched rows (266)
## > =====
## > rows total 59
## distinct: removed 57 rows (97%), 2 rows remaining
left_join() para juntar os dados de voto por partido de questão (a) com a tabela de HDI de questão (b).IDH <- IDH %>% mutate(NM_UE=case_when(NM_UE=="BOAVISTA"~"BOA VISTA",
NM_UE=="RORAINOPOLIS"~"RORAINÓPOLIS",
TRUE~NM_UE))
## mutate: changed 2 values (13%) of 'NM_UE' (0 new NA)
resultados_totais_partidos_IDH <- resultados_totais_partidos %>%
left_join(IDH, by="NM_UE")
## left_join: added one column (IDH)
## > rows only in x 0
## > rows only in y ( 0)
## > matched rows 325
## > =====
## > rows total 325
resultados_totais_partidos_IDH
resultados_totais_partidos_IDH %>%
filter(SG_PARTIDO=="PMDB") %>%
ggplot() +
geom_point(aes(x=IDH, y=Pct_Votos)) +
ggtitle("IDH do Município e Porcentagem de Votos do PMDB") +
xlab("IDH") +
ylab("Porcentagem de Votos do PMDB") +
theme_classic()
## filter: removed 311 rows (96%), 14 rows remaining
resultados_totais_partidos_IDH %>%
filter(SG_PARTIDO=="PMDB") %>%
ggplot() +
geom_point(aes(x=IDH, y=Pct_Votos, size=Tot_Votos)) +
ggtitle("IDH do Município e Porcentagem de Votos do PMDB") +
xlab("IDH") +
ylab("Porcentagem de Votos do PMDB") +
theme_classic()
## filter: removed 311 rows (96%), 14 rows remaining
resultados_totais_partidos_IDH %>%
filter(SG_PARTIDO=="PMDB") %>%
ggplot() +
geom_point(aes(x=IDH, y=Pct_Votos, colour=Tot_Votos)) +
scale_colour_gradient(low="#fee6ce", high="#a63603") +
ggtitle("IDH do Município e Porcentagem de Votos do PMDB") +
xlab("IDH") +
ylab("Porcentagem de Votos do PMDB") +
theme_classic()
## filter: removed 311 rows (96%), 14 rows remaining